package com.gzhryc.shared_device.oem.h5.mng.controllers.device;

import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.data.dto.SelectResult;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.shared_device.iot.code.dao.db.IOTServerNode;
import com.gzhryc.shared_device.iot.code.dao.enums.EAliyunLinkType;
import com.gzhryc.shared_device.iot.code.dao.enums.IOTServerNodeEnum;
import com.gzhryc.shared_device.iot.code.services.IOTServerNodeService;
import com.gzhryc.shared_device.iot.code.services.dto.IOTServerNodeSearch;
import com.gzhryc.shared_device.iot.core.aliyun.models.AliyunIOTConfig;
import com.gzhryc.shared_device.iot.core.enums.EIOTType;
import com.gzhryc.shared_device.iot.core.hryc.models.HRYCIOTConfig;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.oem.h5.mng.WebConstants;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

public class IOTServerNodeController {

    static Logger log = Logger.getLogger(IOTServerNodeController.class);

    @Route(value = "/device/iot_node/list.html")
    public String list(HttpServletRequest request) {
        return "/device/iot_node/list.html";
    }

    @Route(value = "/device/iot_node/list.data")
    public ListResult<IOTServerNode> listData(HttpServletRequest request) {
        ListResult<IOTServerNode> result = new ListResult<>(DtoConstants.NULL_DATA,"暂无数据");
        Integer pageNo = WebUtils.getInteger(request, "page", 1);
        Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);
        IOTServerNodeSearch search = WebUtils.getParameter(request, IOTServerNodeSearch.class);
        result.getBody().setTotal(IOTServerNodeService.self().countJoinBySearch(search));
        List<IOTServerNode> data = IOTServerNodeService.self().findJoinBySearch(search, pageNo, pageLimit);
        if(data != null && data.size() > 0) {
            result.setCode(DtoConstants.SUCCESS, null);
            result.getBody().setData(data);
        }
        return result;
    }

    @Route(value="/device/iot_node/add.html")
    public String add(HttpServletRequest request) {
        request.setAttribute("iotTypeList", EIOTType.values());
        return "/device/iot_node/edit.html";
    }

    @Route(value = "/device/iot_node/add.do")
    public AjaxResult doAdd(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "新增失败");
        IOTServerNode iotServerNode = WebUtils.getParameter(request, IOTServerNode.class);
        try {
            if (IOTServerNodeService.self().add(iotServerNode)) {
                result.setCode(DtoConstants.SUCCESS, null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route(value="/device/iot_node/update.html")
    public String update(HttpServletRequest request) {
        Long id = WebUtils.getLong(request, "id");
        if(id != null) {
            IOTServerNode iotServerNode = IOTServerNodeService.self().getJoinById(id);
            if(iotServerNode != null) {
                WebUtils.setAttribute(request, iotServerNode);
            }
        }
        request.setAttribute("stateList", IOTServerNodeEnum.State.values());
        request.setAttribute("iotTypeList", EIOTType.values());
        return "/device/iot_node/edit.html";
    }

    @Route(value = "/device/iot_node/update.do")
    public AjaxResult doUpdate(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "修改失败");
        IOTServerNode iotServerNode = WebUtils.getParameter(request, IOTServerNode.class);
        try {
            if(IOTServerNodeEnum.State.Usable.index().equals(iotServerNode.getState())){
                //检查配置信息
                IOTServerNode temp = IOTServerNodeService.self().getById(iotServerNode.getId());
                if(temp == null || StringUtils.isBlank(temp.getLinkConfig())){
                    result.setMsg("需要配置连接信息后才能启用");
                    return result;
                }
            }

            if (IOTServerNodeService.self().updateNotNull(iotServerNode)) {
                result.setCode(DtoConstants.SUCCESS, null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route(value="/device/iot_node/config.html")
    public String config(HttpServletRequest request) {
        Long id = WebUtils.getLong(request, "id");
        if(id != null) {
            IOTServerNode iotServerNode = IOTServerNodeService.self().getById(id);
            if(iotServerNode != null) {
                WebUtils.setAttribute(request, iotServerNode);
                if(EIOTType.ALIYUN.index().equals(iotServerNode.getIotType())) {
                    request.setAttribute("linkTypeList", EAliyunLinkType.values());
                    if(StringUtils.isNotBlank(iotServerNode.getLinkConfig())) {
                        AliyunIOTConfig linkConfig = JsonTools.fromJson(iotServerNode.getLinkConfig(), AliyunIOTConfig.class);
                        WebUtils.setAttribute(request, linkConfig);
                    }
                    return "/device/iot_node/config/aliyun.html";
                }else if(EIOTType.HRYC_SMART.index().equals(iotServerNode.getIotType())) {
                    if(StringUtils.isNotBlank(iotServerNode.getLinkConfig())) {
                        HRYCIOTConfig linkConfig = JsonTools.fromJson(iotServerNode.getLinkConfig(), HRYCIOTConfig.class);
                        WebUtils.setAttribute(request, linkConfig);
                    }
                }
            }
        }
        return "/device/iot_node/config/default.html";
    }

    @Route(value = "/device/iot_node/config.do")
    public AjaxResult doConfig(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "修改失败");
        IOTServerNode iotServerNode = WebUtils.getParameter(request, IOTServerNode.class);
        if (EIOTType.ALIYUN.index().equals(iotServerNode.getIotType())) {
            AliyunIOTConfig linkConfig = WebUtils.getParameter(request, AliyunIOTConfig.class);
            if(StringUtils.isBlank(linkConfig.getRegionId()) || StringUtils.isBlank(linkConfig.getAccessKey()) || StringUtils.isBlank(linkConfig.getAccessSecret())){
                result.setMsg("阿里云主要配置未填写");
                return result;
            }
            if(EAliyunLinkType.MNS.index().equals(linkConfig.getLinkType())){
                if(StringUtils.isBlank(linkConfig.getAccountEndpoint()) || StringUtils.isBlank(linkConfig.getQueueName()) || StringUtils.isBlank(linkConfig.getUid())){
                    result.setMsg("阿里云MNS配置未填写");
                    return result;
                }
            }
            iotServerNode.setLinkConfig(JsonTools.toJson(linkConfig));
        }else if(EIOTType.HRYC_SMART.index().equals(iotServerNode.getIotType())) {
            HRYCIOTConfig linkConfig = WebUtils.getParameter(request, HRYCIOTConfig.class);
            if(StringUtils.isBlank(linkConfig.getIp()) || linkConfig.getPort() == null){
                result.setMsg("物联网主要配置未填写");
                return result;
            }
            iotServerNode.setLinkConfig(JsonTools.toJson(linkConfig));
        }
        try {
            iotServerNode.setState(IOTServerNodeEnum.State.Unusable.index());   //修改配置后，节点将关闭
            if (IOTServerNodeService.self().updateNotNull(iotServerNode)) {
                result.setCode(DtoConstants.SUCCESS, null);
            }
        } catch (LogicException e) {
            result.setMsg(e.getMessage());
        }
        return result;
    }

    @Route(value="/device/iot_node/info.html")
    public String info(HttpServletRequest request) {
        Long id = WebUtils.getLong(request, "id");
        if(id != null) {
            IOTServerNode iotServerNode = IOTServerNodeService.self().getById(id);
            if(iotServerNode != null) {
                WebUtils.setAttribute(request, iotServerNode);
                if(EIOTType.ALIYUN.index().equals(iotServerNode.getIotType())) {
                    if(StringUtils.isNotBlank(iotServerNode.getLinkConfig())) {
                        AliyunIOTConfig linkConfig = JsonTools.fromJson(iotServerNode.getLinkConfig(), AliyunIOTConfig.class);
                        WebUtils.setAttribute(request, linkConfig);
                    }
                }else if(EIOTType.HRYC_SMART.index().equals(iotServerNode.getIotType())) {
                    if(StringUtils.isNotBlank(iotServerNode.getLinkConfig())) {
                        HRYCIOTConfig linkConfig = JsonTools.fromJson(iotServerNode.getLinkConfig(), HRYCIOTConfig.class);
                        WebUtils.setAttribute(request, linkConfig);
                    }
                }
            }
        }
        return "/device/iot_node/info.html";
    }

    @Route(value="/device/iot_node/start.do")
    public AjaxResult doStartUsing(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"启用失败");
        Long id = WebUtils.getLong(request, "id");
        if(id != null) {
            try {
                if(IOTServerNodeService.self().start(id)) {
                    result.setCode(DtoConstants.SUCCESS, null);
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }
        return result;
    }

    @Route(value="/device/iot_node/close.do")
    public AjaxResult doClose(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"关闭失败");
        Long id = WebUtils.getLong(request, "id");
        if(id != null) {
            try {
                if(IOTServerNodeService.self().close(id)) {
                    result.setCode(DtoConstants.SUCCESS, null);
                }
            } catch (LogicException e) {
                result.setMsg(e.getMessage());
            }
        }
        return result;
    }

    @Route(value="/device/iot_node/del.do")
    public AjaxResult doDelete(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"删除失败");
        Long id = WebUtils.getLong(request, "id");
        if(id != null) {
            if(IOTServerNodeService.self().deleteById(id)) {
                result.setCode(DtoConstants.SUCCESS, null);
            }
        }
        return result;
    }

    @Route(value="/device/iot_node/select.data")
    public SelectResult selectData(HttpServletRequest request) {
        SelectResult result = new SelectResult(DtoConstants.SUCCESS);
        String term = request.getParameter("term");
        Integer page = WebUtils.getInteger(request, "page", 1);
        IOTServerNodeSearch search = WebUtils.getParameter(request, IOTServerNodeSearch.class);
        search.setName(term);
        Long total = IOTServerNodeService.self().countJoinBySearch(search);
        List<IOTServerNode> list = IOTServerNodeService.self().findJoinBySearch(search, page, WebConstants.PAGE_LIMIT);
        if (list != null && list.size() > 0) {
            for (IOTServerNode iotNode : list) {
                SelectResult.Item item = new SelectResult.Item();
                item.setId(iotNode.getId().toString());
                item.setText(iotNode.getName());

                result.getBody().getData().add(item);
            }
        }
        result.getBody().setPage(page);
        result.getBody().setLimit(WebConstants.PAGE_LIMIT);
        result.getBody().setTotal(total);
        return result;
    }

    @Route(value="/device/iot_node/cache/clear.do")
    public AjaxResult clearCache(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR,"清除缓存失败");
        Long id = WebUtils.getLong(request, "id");
        if(id != null) {
            IOTServerNode iotNode = IOTServerNodeService.self().getById(id);
            if(iotNode != null) {}
        }
        return result;
    }
}
